import pyautogui
from PIL import ImageGrab
import time


def select_region_interactively():
    """
    交互式选择屏幕区域
    返回bbox格式的区域坐标
    """
    print("请在5秒内将鼠标移动到区域的左上角...")
    time.sleep(5)
    x1, y1 = pyautogui.position()
    print(f"左上角坐标: ({x1}, {y1})")

    print("请在5秒内将鼠标移动到区域的右下角...")
    time.sleep(5)
    x2, y2 = pyautogui.position()
    print(f"右下角坐标: ({x2}, {y2})")

    # 确保坐标顺序正确
    left = min(x1, x2)
    top = min(y1, y2)
    right = max(x1, x2)
    bottom = max(y1, y2)

    bbox = (left, top, right, bottom)
    print(f"选择的区域: {bbox}")

    # 截取并保存选定的区域
    region_img = ImageGrab.grab(bbox=bbox)
    region_img.save('selected_region.png')
    print("区域截图已保存为 'selected_region.png'")

    return bbox

# 使用示例
selected_bbox = select_region_interactively()